﻿using System.Linq;
using System.Web.Mvc;
using MusicStore.WebMVC.Models;
using MusicStore.WebMVC.ViewModels;

namespace MusicStore.WebMVC.Controllers
{
    public class ShoppingCartController : BaseController
    {
        //
        // GET: /ShoppingCart/

        public ViewResult Index()
        {
            var cart = ShoppingCart.GetCart(this.HttpContext);

            //set up out view model
            var viewModel = new ShoppingCartViewModel
            {
                CartItems = cart.GetCartItems(),
                CartTotal = cart.GetTotal()
            };

            return View(viewModel);
        }

        // get: /store/addtocart/5

        public ActionResult AddToCart(int id)
        { 
            //retrieve the album from db
            var album = db.Albums.Find(id);

            //add it to the shopping cart
            var cart = ShoppingCart.GetCart(this.HttpContext);

            cart.AddToCart(album);

            //go back to main store page form more shopping
            return RedirectToAction("Index");
        }

        //ajax: /shoppingcart/removefromcart/5

        [HttpPost]
        public ActionResult RemoveFromCart(int id)
        { 
            //remove the item from cart
            var cart = ShoppingCart.GetCart(this.HttpContext);

            //get name of album to display confirmation
            var albumName = db.Carts.Single(c=>c.RecordId == id).Album.Title;

            //remove from cart
            int itemCount = cart.RemoveFromCart(id);

            //display the confirmation message
            var results = new ShoppingCartRemoveViewModel
            {
                Message = Server.HtmlEncode(albumName) + " has been remove from your cart",
                CartTotal = cart.GetTotal(),
                CartCount = cart.GetCount(),
                ItemCount = itemCount,
                DeleteId = id
            };

            return Json(results);
        }

        //get: /shoppingcart/cartsummary

        [ChildActionOnly]
        public ActionResult CartSummary()
        {
            var cart = ShoppingCart.GetCart(this.HttpContext);

            //ViewBag.CartCount = cart.GetCount(); extension methods cannot be dynamic dispatched

            ViewData["CartCount"] = cart.GetCount();

            ViewBag.CartCount = cart.GetCount().ToString();

            return PartialView("CartSummary");
        }
    }
}
